package uiadds;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView.LayoutParams;

public class ThumbStick extends View{

	private Paint mPaint;
	private int height = 80;
	private int width = 80;
	private Point orig = new Point(40, 40);
	private double angle = 0;
	private double mag = 0;
	
	public ThumbStick(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		mPaint = new Paint();
	}
	
	@Override
	protected void onDraw(Canvas canvas)
	{
		super.onDraw(canvas);
		mPaint.setColor(Color.BLUE);
		canvas.drawCircle(width/2, height/2, 40, mPaint);
		mPaint.setColor(Color.BLACK);
		canvas.drawCircle(width/2, height/2, 5, mPaint);
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
	    if(getLayoutParams().width==LayoutParams.WRAP_CONTENT)
	    {
	        width = 80;
	    }
	    else if((getLayoutParams().width==LayoutParams.MATCH_PARENT)||(getLayoutParams().width==LayoutParams.FILL_PARENT))
	    {
	        width = MeasureSpec.getSize(widthMeasureSpec);
	    }
	    else
	        width = getLayoutParams().width;

	    if(getLayoutParams().height==LayoutParams.WRAP_CONTENT)
	    {
	    	height = 80;
	    }
	    else if((getLayoutParams().height==LayoutParams.MATCH_PARENT)||(getLayoutParams().height==LayoutParams.FILL_PARENT))
	    {
	        height = MeasureSpec.getSize(heightMeasureSpec);
	    }
	    else
	        height = getLayoutParams().height;

	    orig.set(width/2, height/2);
	    setMeasuredDimension(width|MeasureSpec.EXACTLY, height|MeasureSpec.EXACTLY);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		float xpos = event.getX() - orig.x;
		float ypos = orig.y - event.getY();
		
		if(event.getAction() == MotionEvent.ACTION_UP
				|| xpos > 40 || ypos > 40)
		{
			angle = 0;
			mag = 0;
		}
		else
		{
			angle = Math.atan2(ypos, xpos)*180/Math.PI;
			mag = Math.sqrt(xpos*xpos + ypos*ypos);
			Log.d("", ""+event.getAction());
			Log.d("", "Direction = " + mag + "<" + angle);
		}
		return true;
	}	
	
	public double getAngle()
	{
		return angle;
	}
	
	public double getMagnitude()
	{
		return mag;
	}
}
